package com.example.booksdeal.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.booksdeal.BmobDBO.BooksDetail;
import com.example.booksdeal.R;
import com.example.booksdeal.basic.BooksDetailActivity;
import com.example.booksdeal.basic.BooksListActivity;
import com.example.booksdeal.util.DBOpenHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SQLQueryListener;

public class F1Fragment extends Fragment {

    private DBOpenHelper dbOpenHelper;  //声明DBOpenHelper对象
    private LinearLayout mainall;
    private String getName,getPrice,getFuc,getHownew,getImg,getTime,username;
    private int book_id;
    private GridView gridView;
    private EditText searchcontext;
    private Button search;
    private SQLiteDatabase db;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.f1_fragment,container,false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getActivity().getIntent().getExtras();
        username = bundle.getString("username");
        initview(view);
    }

    private void initview(View view) {

        gridView = view.findViewById(R.id.newlist);
        mainall = view.findViewById(R.id.button1);
        searchcontext = view.findViewById(R.id.searchcontext);
        search = view.findViewById(R.id.search);
        dbOpenHelper = new DBOpenHelper(getActivity(),"db_booksdeal.db",null,1);  //实例化DBOpenHelper对象，用来创建数据库
        db = dbOpenHelper.getWritableDatabase();
        final ArrayList<HashMap<String,Object>> listItem = new ArrayList<HashMap<String, Object>>();
        BmobQuery<BooksDetail> query = new BmobQuery<>();
        String dql = "select * from BooksDetail order by -createdAt";
        query.setSQL(dql);
        query.doSQLQuery(new SQLQueryListener<BooksDetail>(){
            @Override
            public void done(BmobQueryResult<BooksDetail> bmobQueryResult, BmobException e) {
                if (e == null) {
                    List<BooksDetail> object = (List<BooksDetail>) bmobQueryResult.getResults();
                    if (object != null && object.size() > 0) {
                        for (int i = 0; i < object.size(); i++) {
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("key",object.get(i).getObjectId());
                        map.put("id", object.get(i).getBook_id());
                        map.put("name", object.get(i).getBook_name());
                        map.put("price", object.get(i).getBook_price());
                        map.put("func", object.get(i).getBook_fuc());
                        map.put("hownew", object.get(i).getBook_hownew());
                        map.put("image", object.get(i).getBook_img());
                        map.put("time", object.get(i).getCreatedAt());
                        listItem.add(map);
                        SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), listItem, R.layout.new_book_item,
                                new String[]{"name", "price", "func", "hownew", "image", "time"}, new int[]{R.id.bname, R.id.price, R.id.getway, R.id.hownew, R.id.image, R.id.time});
                        setListViewHeight(gridView, simpleAdapter, listItem.size());
                        gridView.setAdapter(simpleAdapter);
                        //添加每个item点击事件处理
                        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent = new Intent(getActivity(), BooksDetailActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  //只启动一个activity
                                Bundle bundle = new Bundle();
                                bundle.putString("id", listItem.get(i).get("key").toString());
                                bundle.putString("username", username);
                                intent.putExtras(bundle);
                                startActivity(intent);
                            }
                        });
                        }
                    }
                }
            }
        });
//        Cursor cursor = db.query("BooksDetail",new String[]{"id","book_name","book_price","book_fuc","book_hownew","book_img","time"},null,null,null,null,"time desc","6");
//        if (cursor != null && cursor.getCount() > 0){
//            while (cursor.moveToNext()){
//                book_id = cursor.getInt(cursor.getColumnIndex("id"));
//                getName = cursor.getString(cursor.getColumnIndex("book_name"));
//                getPrice = '￥' + cursor.getString(cursor.getColumnIndex("book_price"));
//                getFuc = cursor.getString(cursor.getColumnIndex("book_fuc"));
//                getHownew = cursor.getString(cursor.getColumnIndex("book_hownew"));
//                getImg = cursor.getString(cursor.getColumnIndex("book_img"));
//                Log.i("test","getImg" + getImg);
//                getTime = cursor.getString(cursor.getColumnIndex("time"));
//                HashMap<String,Object> map = new HashMap<String,Object>();
//                map.put("id",book_id);
//                map.put("name",getName);
//                map.put("price",getPrice);
//                map.put("func",getFuc);
//                map.put("hownew",getHownew);
//                map.put("image",getImg);
//                map.put("time",getTime);
//                listItem.add(map);
//                SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(),listItem,R.layout.new_book_item,
//                        new String[]{"name","price","func","hownew","image","time"},new int[]{R.id.bname,R.id.price,R.id.getway,R.id.hownew,R.id.image,R.id.time});
//                setListViewHeight(gridView, simpleAdapter, listItem.size());
//                gridView.setAdapter(simpleAdapter);
//                //添加每个item点击事件处理
//                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                        Intent intent = new Intent(getActivity(), BooksDetailActivity.class);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  //只启动一个activity
//                        Bundle bundle = new Bundle();
//                        bundle.putString("id", listItem.get(i).get("id").toString());
//                        bundle.putString("username",username);
//                        intent.putExtras(bundle);
//                        startActivity(intent);
//                    }
//                });
//            }
//        }
//        cursor.close();
//        db.close();

        mainall.setOnClickListener(this::onClick);
        search.setOnClickListener(this::onClick);
    }

    // 设置GridView能显示个数的高度
    private void setListViewHeight(GridView gridView, SimpleAdapter adapter, int count) {
        if (adapter == null) {
            return;
        }
        Log.i("Test", "count: " + count);
        int totalHeight = 0;
        int col = 2;
        for (int i = 0; i < count; i += 2) {
            View listItem = adapter.getView(i, null, gridView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
            Log.i("Test", "i: " + i);
            Log.i("Test", "totalHeight: " + totalHeight);
        }
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(20, 20, 20, 10);
        params.height = totalHeight;
        gridView.setLayoutParams(params);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                All();
                break;
            case R.id.search:
                Search();
                break;
        }
    }

    // 全部
    public void All() {
        Bundle bundle = new Bundle();
        bundle.putString("username",username);
        Intent intent = new Intent(getActivity(), BooksListActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    // 搜索
    public void Search() {
        Intent intent = new Intent(getActivity(),BooksListActivity.class);
        intent.putExtra("searchcontext",searchcontext.getText().toString());
        intent.putExtra("username",username);
        startActivity(intent);
        searchcontext.setText("");
    }
}
